package com.tanhua.sso.service.impl;

import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.service.UsersService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author 西楚霸王
 * @date 2020/12/3 8:56
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    UserService userService;

    @Autowired
    SmsService smsService;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public Boolean sendVerificationCode(String token) {
        //查询到用户的手机号
        User user = this.userService.queryUserByToken(token);
        if (null == user){
            return false;
        }

        String mobile = user.getMobile();
        Map<String,Object> result = this.smsService.sendCheckCode(mobile);

        return ((Integer)result.get("code")).intValue() == 3;
    }

    @Override
    public Boolean checkVerificationCode(String code, String token) {
        //查询到用户的手机号
        User user = this.userService.queryUserByToken(token);
        if (null == user){
            return false;
        }

        String redisKey = SmsService.REDIS_KEY_PREFIX + user.getMobile();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (StringUtils.equals(value,code)){
            //验证码正确
            this.redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateNewMobile(String token, String newPhone) {
        //查询到用户的手机号
        User user = this.userService.queryUserByToken(token);
        if (null == user){
            return false;
        }
        return this.userService.updateNewMobile(user.getId(),newPhone);
    }
}
